<template>
  <common-dialog
    :dialog-visible.sync="visible"
    title="人员选择"
    width="1150px"
    fit-content
    @confirm="handleConfirm"
  >
    <el-form :inline="true" :model="filter" size="small" @submit.native.prevent>
      <el-form-item label="姓名">
        <el-input v-model="filter.userName" placeholder="请输入姓名" clearable @keydown.enter.native="onSubmit" />
      </el-form-item>
      <el-form-item label="账号">
        <el-input v-model="filter.userCode" placeholder="请输入账号" clearable @keydown.enter.native="onSubmit" />
      </el-form-item>
      <el-form-item>
        <el-button style="margin-left:12px" icon="el-icon-search" type="primary" size="small" @click="onSubmit">查询</el-button>
        <el-button style="margin-left:12px" size="small" @click="onReset">重置</el-button>
      </el-form-item>
    </el-form>
    <div class="data-container">
      <lb-table
        ref="multipleTable"
        v-loading="loading"
        class="data-normal"
        :column="tableColumns"
        :data="tableData"
        background
        pagination
        layout="total, sizes, prev, pager, next, jumper"
        :page-sizes="[5, 10, 20, 30]"
        :current-page.sync="currentPage"
        :total="total"
        :page-size="pageSize"
        row-key="id"
        @size-change="handleSizeChange"
        @p-current-change="handleCurrentChange"
        @selection-change="handleSelectionChange"
        @row-click="handleRowClick"
        @row-dblclick="handleRowDbClick"
      />
      <div v-if="showHistory" class="line" />
      <div v-if="showHistory" class="data-history">
        <el-card class="box-card">
          <span class="data-history-title">
            最近
          </span>
          <lb-table
            v-if="historyData && historyData.length"
            ref="historyTable"
            class="history-table"
            :stripe="false"
            :column="historyTableColumns"
            :data="historyData"
            row-key="id"
            @selection-change="handleSelectionChange"
            @row-click="handleHistoryRowClick"
            @cell-dblclick="handleRowDbClick"
          />
          <el-empty v-else class="history_empty" description="暂无数据" />
        </el-card>
      </div>
    </div>
    <div v-if="multi">
      <el-tag
        v-for="(tag,index) in fullMultipleSelection"
        :key="index"
        closable
        :disable-transitions="true"
        style="margin-right:8px;"
        @close="handleTagClose(tag, index)"
      >
        {{ tag.user_name }}
      </el-tag>
    </div>
  </common-dialog>
</template>
<script>
import {
  getEmployeeList,
  invokeMethod,
  invokeMethodMore
} from '@admin/api/common'
import {
  collectPluck,
  getUnionArr
} from '@admin/utils/index'
import DataStorage from '@admin/utils/dataStorage'
export default {
  name: 'UserDialog',
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    },
    multi: {
      type: Boolean,
      default: true
    },
    showHistory: {
      type: Boolean,
      default: true
    },
    outerTag: {
      type: String,
      default: '0'
    },
    user2Local: {
      type: String,
      default: '0'
    }
  },
  data() {
    return {
      loading: false,
      visible: false,
      filter: {
        userCode: '',
        userName: ''
      },
      currentPage: 1,
      pageSize: 10,
      ignoreSelection: false,
      multipleSelection: [],
      fullMultipleSelection: [], // 全量选择
      tableData: [],
      dataStorage: null,
      historyData: []
    }
  },
  computed: {
    tableColumns: function() {
      const columns = [
        {
          prop: 'user_name',
          label: '姓名'
        },
        {
          prop: 'user_code',
          label: '账号'
        },
        {
          prop: 'deptName',
          label: '部门名称'
        }
      ]
      if (this.multi) {
        columns.unshift({
          type: 'selection',
          width: 55,
          'reserve-selection': true
        })
      }
      return columns
    },
    historyTableColumns: function() {
      const columns = [
        {
          prop: 'userName',
          label: '姓名',
          minWidth: 200,
          render: (h, scope) => {
            return (
              <span title={'部门：' + scope.row.deptName}>
                <i class='el-icon-user' />&nbsp;&nbsp;
                { scope.row.user_code }&nbsp;{ '(' + scope.row.user_name + ')' }
              </span>
            )
          }
        }
      ]
      if (this.multi) {
        columns.unshift({
          type: 'selection',
          width: 50,
          'reserve-selection': true
        })
      }
      return columns
    },
    fullSelectionIds: function() {
      return collectPluck(this.fullMultipleSelection, 'id')
    }
  },
  watch: {
    dialogVisible: {
      immediate: true,
      handler: function(newvalue) {
        this.visible = newvalue
        if (!newvalue) {
          this.currentPage = 1
          this.pageSize = 10
          this.total = 0
          this.filter.userCode = ''
          this.filter.userName = ''
          this.tableData = []
          this.multipleSelection = []
          this.fullMultipleSelection = []
        } else {
          this.historyData = this.dataStorage.getStorage().reverse()
        }
      }
    },
    visible: function(newvalue) {
      this.$emit('update:dialogVisible', newvalue)
    },
    multipleSelection: function(newValue, oldValue) {
      if (this.ignoreSelection) {
        // 换页忽略
        return
      }
      // 新增
      newValue.forEach(item => {
        if (!this.fullSelectionIds.includes(item.id)) {
          this.fullMultipleSelection.push(item)
        }
      })
      // 对比数组删除
      const deleteIds = []
      oldValue.forEach(item => {
        if (!collectPluck(newValue, 'id').includes(item.id)) {
          deleteIds.push(item.id)
        }
      })
      this.fullMultipleSelection = this.fullMultipleSelection.filter(item => {
        return !deleteIds.includes(item.id)
      })
    }
  },
  mounted: function() {
    this.dataStorage = new DataStorage({
      name: 'user_history',
      count: 10,
      distinctKey: 'user_code'
    })
  },
  methods: {
    handleHistoryRowClick(row) {
      if (this.multi) {
        this.$refs.historyTable.toggleRowSelection(row)
      }
    },
    close() {
      this.visible = false
    },
    setIgnore() {
      this.ignoreSelection = true
      setTimeout(() => {
        this.ignoreSelection = false
      }, 100)
    },
    // 选中回填
    backFillChecked() {
      this.fullMultipleSelection.forEach(item => {
        this.$refs.multipleTable.toggleRowSelection(item)
      })
    },
    handleSizeChange(val) {
      this.currentPage = 1
      this.pageSize = val
      this.getOaList()
    },
    handleCurrentChange() {
      this.getOaList()
    },
    handleSelectionChange(val) {
      setTimeout(() => {
        this.multipleSelection = val
      })
    },
    handleTagClose(item, index) {
      this.fullMultipleSelection.splice(index, 1)
      this.$refs.multipleTable.toggleRowSelection(item)
    },
    handleRowClick(row, column, event) {
      if (this.multi) {
        this.$refs.multipleTable.toggleRowSelection(row)
      }
    },
    handleRowDbClick(row, column, event) {
      // 单选时双击关闭当前弹框
      if (!this.multi) {
        this.showHistory && this.dataStorage.setStorage([row])
        if (this.user2Local == '1') {
          const users = [row].map(i => {
            delete i.update_time
            return i
          })
          const params = {
            methodId: '698533841412820992',
            dataset: users
          }
          invokeMethodMore(params).then(res => {
            this.$emit('confirm', res.data, this.close)
          })
        } else {
          this.$emit('confirm', [row], this.close)
        }
      }
    },
    handleConfirm() {
      if (this.multi) {
        const selected = this.fullMultipleSelection
        if (selected.length === 0) {
          this.$$message('请选择人员')
          return
        }
        this.showHistory && this.dataStorage.setStorage(selected)
        if (this.user2Local == '1') {
          const users = selected.map(i => {
            delete i.update_time
            return i
          })
          const params = {
            methodId: '698533841412820992',
            dataset: users
          }
          invokeMethodMore(params).then(res => {
            this.$emit('confirm', res.data, this.close)
          })
        } else {
          this.$emit('confirm', selected, this.close)
        }
      } else {
        const currentRow = this.$refs.multipleTable.currentRow || this.$refs.historyTable.currentRow
        if (!currentRow) {
          this.$$message('请选择人员')
          return
        }
        this.showHistory && this.dataStorage.setStorage([currentRow])
        if (this.user2Local == '1') {
          const users = [currentRow].map(i => {
            delete i.update_time
            return i
          })
          const params = {
            methodId: '698533841412820992',
            dataset: users
          }
          invokeMethodMore(params).then(res => {
            this.$emit('confirm', res.data, this.close)
          })
        } else {
          this.$emit('confirm', [currentRow], this.close)
        }
      }
    },
    onSubmit() {
      this.currentPage = 1
      this.getOaList()
    },
    onReset() {
      this.filter.userCode = ''
      this.filter.userName = ''
      this.currentPage = 1
      this.tableData = []
    },
    getOaList() {
      if(this.filter.userCode=='' && this.filter.userName==''){
        this.$$message('请输入姓名或账号搜索')
        return
      }
      this.loading = true
      const params = {
        methodId: '1179386853791371264',
        data: {
          pageIndex: this.currentPage,
          pageSize: this.pageSize,
          userCode: this.filter.userCode,
          userName: this.filter.userName,
          outerTag: this.outerTag
        }
      }
      invokeMethod(params).then(res => {
        this.setIgnore()
        setTimeout(() => {
          this.backFillChecked()
        }, 100)
        this.tableData = res.data.data || []
        this.total = res.data.totalCount
      }).finally(() => {
        this.loading = false
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.config-form{
  &::v-deep{
    .el-form-item__content{
      flex: 1;
    }
  }
}
.data-container{
  display: flex;
  .data-normal{
    flex: 1;
  }
  .line{
    min-width: 2px;
    max-width: 2px;
    background: #EBEEF5;
    margin: 0 20px;
  }
  .data-history{
    min-width: 300px;
    max-width: 300px;
    .data-history-title{
      font-size: 14px;
      transform: translateY(-10px);
      display: inline-block;
    }
    .history_empty{
      width: 80%;
      margin: 0 auto;
      ::v-deep .el-empty__image{
        width: auto;
      }
    }
  }
}
.history-table{
  ::v-deep thead{
    display: none;
  }
}
</style>

